
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" lang="zh_Hans">
  <head>
    <meta http-equiv="X-UA-Compatible" content="IE=Edge" />
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>利用 Django 输出 PDF &#8212; Django 3.2.11.dev 文档</title>
    <link rel="stylesheet" href="../_static/default.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <script type="text/javascript" id="documentation_options" data-url_root="../" src="../_static/documentation_options.js"></script>
    <script type="text/javascript" src="../_static/jquery.js"></script>
    <script type="text/javascript" src="../_static/underscore.js"></script>
    <script type="text/javascript" src="../_static/doctools.js"></script>
    <script type="text/javascript" src="../_static/language_data.js"></script>
    <link rel="index" title="索引" href="../genindex.html" />
    <link rel="search" title="搜索" href="../search.html" />
    <link rel="next" title="复写模板" href="overriding-templates.html" />
    <link rel="prev" title="利用 Django 输出 CSV" href="outputting-csv.html" />



 
<script src="../templatebuiltins.js"></script>
<script>
(function($) {
    if (!django_template_builtins) {
       // templatebuiltins.js missing, do nothing.
       return;
    }
    $(document).ready(function() {
        // Hyperlink Django template tags and filters
        var base = "../ref/templates/builtins.html";
        if (base == "#") {
            // Special case for builtins.html itself
            base = "";
        }
        // Tags are keywords, class '.k'
        $("div.highlight\\-html\\+django span.k").each(function(i, elem) {
             var tagname = $(elem).text();
             if ($.inArray(tagname, django_template_builtins.ttags) != -1) {
                 var fragment = tagname.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + tagname + "</a>");
             }
        });
        // Filters are functions, class '.nf'
        $("div.highlight\\-html\\+django span.nf").each(function(i, elem) {
             var filtername = $(elem).text();
             if ($.inArray(filtername, django_template_builtins.tfilters) != -1) {
                 var fragment = filtername.replace(/_/, '-');
                 $(elem).html("<a href='" + base + "#" + fragment + "'>" + filtername + "</a>");
             }
        });
    });
})(jQuery);(function($) {
    $(document).ready(function() {
        $(".c-tab-unix").on("click", function() {
            $("section.c-content-unix").show();
            $("section.c-content-win").hide();
            $(".c-tab-unix").prop("checked", true);
        });
        $(".c-tab-win").on("click", function() {
            $("section.c-content-win").show();
            $("section.c-content-unix").hide();
            $(".c-tab-win").prop("checked", true);
        });
    });
})(jQuery);</script>
<link rel="stylesheet" href="../_static/console-tabs.css" type="text/css" />
  </head><body>

    <div class="document">
  <div id="custom-doc" class="yui-t6">
    <div id="hd">
      <h1><a href="../index.html">Django 3.2.11.dev 文档</a></h1>
      <div id="global-nav">
        <a title="Home page" href="../index.html">Home</a>  |
        <a title="Table of contents" href="../contents.html">Table of contents</a>  |
        <a title="Global index" href="../genindex.html">Index</a>  |
        <a title="Module index" href="../py-modindex.html">Modules</a>
      </div>
      <div class="nav">
    &laquo; <a href="outputting-csv.html" title="利用 Django 输出 CSV">previous</a>
     |
    <a href="index.html" title="操作指南" accesskey="U">up</a>
   |
    <a href="overriding-templates.html" title="复写模板">next</a> &raquo;</div>
    </div>

    <div id="bd">
      <div id="yui-main">
        <div class="yui-b">
          <div class="yui-g" id="howto-outputting-pdf">
            
  <div class="section" id="s-outputting-pdfs-with-django">
<span id="outputting-pdfs-with-django"></span><h1>利用 Django 输出 PDF<a class="headerlink" href="#outputting-pdfs-with-django" title="永久链接至标题">¶</a></h1>
<p>本文介绍如何用 Django 的视图动态输出 PDF 文件。该功能由绝佳的开源 <a class="reference external" href="https://www.reportlab.com/opensource/">ReportLab</a> Python  PDF 库提供。</p>
<p>动态生成 PDF 文件的优点是你可以为不同的目的创建不同的自定义 PDF——例如，为不同的用户或内容的不同片段生成 PDF。</p>
<p>例如，<a class="reference external" href="http://www2.kusports.com/">kusports.com</a> 用 Django 将自定义的，打印友好的 NCAA 锦标赛树状图生成 PDF 文件，发放给参加三月疯狂竞赛的人。</p>
<div class="section" id="s-install-reportlab">
<span id="install-reportlab"></span><h2>安装 ReportLab<a class="headerlink" href="#install-reportlab" title="永久链接至标题">¶</a></h2>
<p>ReportLab 库可从 <a class="reference external" href="https://pypi.org/project/reportlab/">PyPI</a> 获取。也可以下载 <a class="reference external" href="https://www.reportlab.com/docs/reportlab-userguide.pdf">用户指南</a> （一份 PDF 文件，这不是巧合）。你可以用 <code class="docutils literal notranslate"><span class="pre">pip</span></code> 安装 ReportLab：</p>
<div class="console-block" id="console-block-0">
<input class="c-tab-unix" id="c-tab-0-unix" type="radio" name="console-0" checked>
<label for="c-tab-0-unix" title="Linux/macOS">&#xf17c/&#xf179</label>
<input class="c-tab-win" id="c-tab-0-win" type="radio" name="console-0">
<label for="c-tab-0-win" title="Windows">&#xf17a</label>
<section class="c-content-unix" id="c-content-0-unix">
<div class="highlight-console notranslate"><div class="highlight"><pre><span></span><span class="gp">$ </span>python -m pip install reportlab
</pre></div>
</div>
</section>
<section class="c-content-win" id="c-content-0-win">
<div class="highlight"><pre><span></span><span class="gp">...\&gt;</span> py -m pip install reportlab
</pre></div>
</section>
</div>
<p>在 Python 交互解释器中导入它，测试你的安装是否成功:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="gp">&gt;&gt;&gt; </span><span class="kn">import</span> <span class="nn">reportlab</span>
</pre></div>
</div>
<p>若该命令未抛出任何错误，安装成功。</p>
</div>
<div class="section" id="s-write-your-view">
<span id="write-your-view"></span><h2>编写视图<a class="headerlink" href="#write-your-view" title="永久链接至标题">¶</a></h2>
<p>利用 Django 动态生成 PDF 的关键是 ReportLab API 作用于类文件对象，而 Django 的 <a class="reference internal" href="../ref/request-response.html#django.http.FileResponse" title="django.http.FileResponse"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileResponse</span></code></a> 对象接收类文件对象。</p>
<p>这有个 &quot;Hello World&quot; 示例:</p>
<div class="highlight-default notranslate"><div class="highlight"><pre><span></span><span class="kn">import</span> <span class="nn">io</span>
<span class="kn">from</span> <span class="nn">django.http</span> <span class="kn">import</span> <span class="n">FileResponse</span>
<span class="kn">from</span> <span class="nn">reportlab.pdfgen</span> <span class="kn">import</span> <span class="n">canvas</span>

<span class="k">def</span> <span class="nf">some_view</span><span class="p">(</span><span class="n">request</span><span class="p">):</span>
    <span class="c1"># Create a file-like buffer to receive PDF data.</span>
    <span class="n">buffer</span> <span class="o">=</span> <span class="n">io</span><span class="o">.</span><span class="n">BytesIO</span><span class="p">()</span>

    <span class="c1"># Create the PDF object, using the buffer as its &quot;file.&quot;</span>
    <span class="n">p</span> <span class="o">=</span> <span class="n">canvas</span><span class="o">.</span><span class="n">Canvas</span><span class="p">(</span><span class="n">buffer</span><span class="p">)</span>

    <span class="c1"># Draw things on the PDF. Here&#39;s where the PDF generation happens.</span>
    <span class="c1"># See the ReportLab documentation for the full list of functionality.</span>
    <span class="n">p</span><span class="o">.</span><span class="n">drawString</span><span class="p">(</span><span class="mi">100</span><span class="p">,</span> <span class="mi">100</span><span class="p">,</span> <span class="s2">&quot;Hello world.&quot;</span><span class="p">)</span>

    <span class="c1"># Close the PDF object cleanly, and we&#39;re done.</span>
    <span class="n">p</span><span class="o">.</span><span class="n">showPage</span><span class="p">()</span>
    <span class="n">p</span><span class="o">.</span><span class="n">save</span><span class="p">()</span>

    <span class="c1"># FileResponse sets the Content-Disposition header so that browsers</span>
    <span class="c1"># present the option to save the file.</span>
    <span class="n">buffer</span><span class="o">.</span><span class="n">seek</span><span class="p">(</span><span class="mi">0</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">FileResponse</span><span class="p">(</span><span class="n">buffer</span><span class="p">,</span> <span class="n">as_attachment</span><span class="o">=</span><span class="kc">True</span><span class="p">,</span> <span class="n">filename</span><span class="o">=</span><span class="s1">&#39;hello.pdf&#39;</span><span class="p">)</span>
</pre></div>
</div>
<p>代码和注释应该是不言自明的，但是有几件事值得提一下：</p>
<ul class="simple">
<li>响应会自动基于文件扩展名将 MIME 类型设置为应用程序 <em class="mimetype">application/pdf</em>。这告诉浏览器该文档是个 PDF 文件，而不是 HTML 文件或普通的应用程序 <em class="mimetype">application/octet-stream</em> 二进制内容。</li>
<li>将 <code class="docutils literal notranslate"><span class="pre">as_attachment=True</span></code> 传递给 <code class="docutils literal notranslate"><span class="pre">FileResponse</span></code> 时，它会设置合适的 <code class="docutils literal notranslate"><span class="pre">Content-Disposition</span></code> 头，这将告诉 Web 浏览器弹出一个对话框，提示或确认如何处理该文档，即便设备已配置默认行为。若省略了 <code class="docutils literal notranslate"><span class="pre">as_attachment</span></code> 参数，浏览器会用已配置的用于处理 PDF 的程序或插件来处理该 PDF。</li>
<li>你也可以提供可选参数 <code class="docutils literal notranslate"><span class="pre">filename</span></code>。浏览器的“另存为…”对话框会用到它。</li>
<li>你可以作为第一个参数传递给 <code class="docutils literal notranslate"><span class="pre">canvas.Canvas</span></code> 的缓冲区也能传递给类 <a class="reference internal" href="../ref/request-response.html#django.http.FileResponse" title="django.http.FileResponse"><code class="xref py py-class docutils literal notranslate"><span class="pre">FileResponse</span></code></a> 类来使用 ReportLab API。</li>
<li>注意，所有后续生成 PDF 的方法都是在 PDF 对象上调用的（本例中是 <code class="docutils literal notranslate"><span class="pre">p</span></code>）——而不是在 <code class="docutils literal notranslate"><span class="pre">buffer</span></code> 上调用。</li>
<li>最后，牢记在 PDF 文件上调用 <code class="docutils literal notranslate"><span class="pre">showPage()</span></code> 和 <code class="docutils literal notranslate"><span class="pre">save()</span></code>。</li>
</ul>
<div class="admonition note">
<p class="first admonition-title">注解</p>
<p class="last">ReportLab 不是线程安全的。某些用户已经报告了一些奇怪的 issue，在创建用于生成 PDF 的 Django 视图时，这些视图被多个用户同时访问会出现问题。</p>
</div>
</div>
<div class="section" id="s-other-formats">
<span id="other-formats"></span><h2>其它格式<a class="headerlink" href="#other-formats" title="永久链接至标题">¶</a></h2>
<p>注意，这些例子中没有任何 PDF 特有的数据——只有使用 <code class="docutils literal notranslate"><span class="pre">reportlab</span></code> 的部分。你可以用类似的技巧生成任意格式，只要你能找到对应的 Python 库。也请看看 <a class="reference internal" href="outputting-csv.html"><span class="doc">利用 Django 输出 CSV</span></a>，看看另一个例子中，如何用一些技巧输出文本内容。</p>
<div class="admonition seealso">
<p class="first admonition-title">参见</p>
<p class="last">Django 包提供了一个 <a class="reference external" href="https://djangopackages.org/grids/g/pdf/">包的比较</a> 有助于用 Django 生成 PDF 文件。</p>
</div>
</div>
</div>


          </div>
        </div>
      </div>
      
        
          <div class="yui-b" id="sidebar">
            
      <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
        <div class="sphinxsidebarwrapper">
  <h3><a href="../contents.html">Table of Contents</a></h3>
  <ul>
<li><a class="reference internal" href="#">利用 Django 输出 PDF</a><ul>
<li><a class="reference internal" href="#install-reportlab">安装 ReportLab</a></li>
<li><a class="reference internal" href="#write-your-view">编写视图</a></li>
<li><a class="reference internal" href="#other-formats">其它格式</a></li>
</ul>
</li>
</ul>

  <h4>上一个主题</h4>
  <p class="topless"><a href="outputting-csv.html"
                        title="上一章">利用 Django 输出 CSV</a></p>
  <h4>下一个主题</h4>
  <p class="topless"><a href="overriding-templates.html"
                        title="下一章">复写模板</a></p>
  <div role="note" aria-label="source link">
    <h3>本页</h3>
    <ul class="this-page-menu">
      <li><a href="../_sources/howto/outputting-pdf.txt"
            rel="nofollow">显示源代码</a></li>
    </ul>
   </div>
<div id="searchbox" style="display: none" role="search">
  <h3>快速搜索</h3>
    <div class="searchformwrapper">
    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="转向" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>
    </div>
</div>
<script type="text/javascript">$('#searchbox').show(0);</script>
        </div>
      </div>
              <h3>Last update:</h3>
              <p class="topless">12月 07, 2021</p>
          </div>
        
      
    </div>

    <div id="ft">
      <div class="nav">
    &laquo; <a href="outputting-csv.html" title="利用 Django 输出 CSV">previous</a>
     |
    <a href="index.html" title="操作指南" accesskey="U">up</a>
   |
    <a href="overriding-templates.html" title="复写模板">next</a> &raquo;</div>
    </div>
  </div>

      <div class="clearer"></div>
    </div>
  </body>
</html>